// pages/cart/cart.js
const app = getApp()
const http = app.globalData.http
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    allPrice: 0,
    userId: null
  },

  // 删除商品
  deleteGoods(e) {
    console.log(e);
    const id = e.currentTarget.dataset.id;
    const self = this;
    const newGoodsList = this.goodsList;
    wx.vibrateShort({});
    wx.showModal({
      title: '',
      content: '确认删除该商品？',
      cancelText: '考虑一下',
      cancelColor: '#F33B44',
      confirmText: '是的会胖',
      confirmColor: '#d2d2d2',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${http}/delCarts`,
            data: {
              UserId: self.userId,
              GoodsId: newGoodsList[id].GoodsId
            },
            success(res) {
              // 返回订单号
              console.log(res);
              newGoodsList.splice(id, 1);
              self.goodsList = newGoodsList;
              self.setData({
                goodsList: newGoodsList
              });
              self.computeAllPrice();
              console.log(newGoodsList);
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 计算总价
  computeAllPrice(){
    let price = 0;
    const goodsList = this.goodsList;
    goodsList.forEach(item => {
      price += item.GoodsPrice * item.Count;
    })
    this.allPrice = price;
    this.setData({
      allPrice: price
    });
    console.log(price, 'price')
    console.log(this.allPrice, 'allPrice');
  },

  // 下单
  order(){
    const self = this;
    wx.showModal({
      title: '',
      content: '确认下单？',
      cancelText: '再看看',
      cancelColor: '#d2d2d2',
      confirmText: '确认',
      confirmColor: '#F33B44',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${http}/addUserOrder`,
            data: {
              UserId: self.userId
            },
            success(res) {
              // 返回订单号
              const orderId = res.data;
              console.log(orderId,'订单号');

              // globalData 存储订单信息
              const orderArr = getApp().globalData.order;
              const orderObj = {
                orderId: orderId,
                countPrice: self.allPrice
              }
              orderArr.push(orderObj);
              getApp().globalData.order = orderArr;

              // 发送商品订单请求
              self.goodsList.forEach(item => {
                wx.request({
                  url: `${http}/addOrder`,
                  data: {
                    OrderId: orderId,
                    GoodsId: item.GoodsId,
                    Count: item.Count
                  },
                  success(res) {
                    console.log(res)
                    if(res.data==true){
                      console.log('aa')
                      self.goodsList = [];
                      self.setData({
                        goodsList: [],
                      })
                      self.computeAllPrice();
                      wx.showToast({
                        title: '下单成功',
                      })
                    }
                    // 成功下单清空购物车
                    // wx.request({
                    //   url: 'http://10.110.5.9:3000/seeTea/delAllCarts',
                    //   data: {
                    //     UserId: self.userId
                    //   },
                    //   success(res){
                    //     self.goodsList = [];
                    //     self.setData({
                    //       goodsList: []
                    //     })
                    //     self.computeAllPrice();
                    //   }
                    // })
                  }
                })
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户取消下单')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 页面加载时获取用户id
    const self = this;
    wx.getStorage({
      key: 'userId',
      success: function(res) {
        self.userId = res.data;
        self.setData({
          userId: res.data
        })
        console.log(self.userId)
        // 页面加载时获取购物车商品信息
        wx.request({
          url: `${http}/showOneCarts`,
          data: {
            UserId: self.userId
          },
          success(res) {
            self.goodsList = res.data;
            self.setData({
              goodsList: res.data
            })
            // 商品信息
            console.log(res);
            self.computeAllPrice();
          }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const self = this;
    wx.request({
      url: `${http}/showOneCarts`,
      data: {
        UserId: self.userId
      },
      success(res) {
        self.goodsList = res.data;
        self.setData({
          goodsList: res.data
        })
        // 商品信息
        console.log(res);
        self.computeAllPrice();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})